import { FC, Ref, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { EchartFlawMapT, FlawTypeSiteT, lotMapEchartT, Sheet, SheetAndFlawSizeT } from '@/typings/global';
import * as echarts from 'echarts';
import './index.less';
import { optConfig } from './option';
import { useStores } from '@/stores';
import { observer } from 'mobx-react-lite';
import { getSheetAndFlawPageNumBack } from '@/api/lot-detail-page';
import { MessageWaring } from '@/utils/tool';

interface ChartsOptionConf {
  onRef: Ref<unknown> | undefined;
  type: EchartFlawMapT;
  //   onSubmit: (sheetId: any, flawUid) => void;
}

const LotFlawMap: React.FC<ChartsOptionConf> = (chartsProps: ChartsOptionConf) => {
  const { lotStore, commonStore } = useStores();
  const [options, setOptions] = useState<any>(optConfig);
  const myChartRef = useRef<echarts.ECharts>();
  const canvasRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    initChart();
  }, []);

  // 右键显示菜单
  const initChart = () => {
    const canvasDom = canvasRef.current;
    if (canvasDom) {
      myChartRef.current = echarts.init(canvasDom);
      const seriesData = lotStore.lotFlawSeriesData;
      const opt = { ...optConfig } as any;
      const { xMin, xMax, yMin, yMax } = lotStore.lotOptMinMax;
      opt.series[0].data = seriesData; // 缺陷集合
      opt.xAxis[0].min = xMin; // x最小坐标，x最大坐标，y最小坐标，y最大坐标
      opt.xAxis[0].max = xMax;
      opt.yAxis[0].min = yMin;
      opt.yAxis[0].max = yMax;
      setOptions(opt);

      myChartRef.current?.setOption(opt);
      myChartRef.current?.on('click', function (params) {
        const flawRow = params.data as lotMapEchartT; // [0,1,2]
        lookLocationByClickFlawLot(flawRow);
      });
    }
  };

  /**
   * 通过点击缺陷地图的缺陷点,定位这个缺陷属于哪一片，定位对应哪一个缺陷卡片
   * @param flawRow
   */
  const lookLocationByClickFlawLot = (flawRow: lotMapEchartT) => {
    const { uid, sheetId, station } = flawRow;
    if(!sheetId){
      return  MessageWaring(`uid=${uid}缺陷,对应的sheetId为空,点击失效！`)
    }
    const commitParams = {
      sheetId,
      station,
      uid: uid,
      lotId: lotStore.lotId,
      layerId: lotStore.layerId,
      sheetPageSize: lotStore.sheet.pageSize,
      flawPageSize: lotStore.card.pageSize
    };
    let flawTypeParams = [] as any;
    if (station == FlawTypeSiteT.doff) {
      flawTypeParams = { flawTypeList: lotStore.checkedFlawTypePmp };
    } else {
      flawTypeParams = lotStore.flawTypeStorage[station as string][0] == 'all' ? {} : { flawTypeList: lotStore.flawTypeStorage[station as string] };
    }
    const mergeParams = Object.assign(commitParams, flawTypeParams) as SheetAndFlawSizeT;
    requestSheetPageNumAndCardNum(mergeParams, station, sheetId, uid);
  };

  /**
   * 获取片列表的pageNum，和缺陷的pageNum
   * @param mergeParams
   * @param station
   * @param sheetId
   * @param uid
   */
  const requestSheetPageNumAndCardNum = async (mergeParams: SheetAndFlawSizeT, station: string, sheetId: number, uid: number) => {
    const backRes = await getSheetAndFlawPageNumBack(mergeParams);
    const { sheetPageNum, flawPageNum } = backRes.data;
    lotStore.card.station = station as string;
    lotStore.card.flawIdChecked = uid as number;
    lotStore.changeSheetListReq(lotStore.lotId, commonStore, sheetId, sheetPageNum, flawPageNum);
  };

  // 更新option里的内容
  const changeOption = paramsOpt => {
    console.log('片缺陷地图--重新绘制的option:', JSON.parse(JSON.stringify(paramsOpt)));
    const { seriesData } = paramsOpt;
    const opt = { ...optConfig };
    try {
      if (seriesData) {
        opt.xAxis[0].min = lotStore.lotOptMinMax.xMin;
        opt.xAxis[0].max = lotStore.lotOptMinMax.xMax;
        opt.yAxis[0].min = lotStore.lotOptMinMax.yMin;
        opt.yAxis[0].max = lotStore.lotOptMinMax.yMax;
        opt.yAxis[1].min = lotStore.lotOptMinMax.qrMin;
        opt.yAxis[1].max = lotStore.lotOptMinMax.qrMax;

        opt.series[0].data = seriesData;
      }
      //  画横线
      (opt as any).series[1].markLine.data = [
        [
          {
            coord: [lotStore.lotOptMinMax?.xMin, lotStore.sheet.headMd]
          },
          {
            coord: [lotStore.lotOptMinMax?.xMax, lotStore.sheet.headMd]
            // symbol: 'none',
          }
        ]
      ];
      setOptions(opt);
      myChartRef.current?.setOption(opt, { notMerge: true });
    } catch (error) {
      console.log(error);
    }
  };

  //   更新红线(注意这里也有一个弊端，那就是每次更新红线时就会全部重新绘制图像)
  useEffect(() => {
    const opt = { ...options } as any;

    const zoomInfo = myChartRef.current?.getOption().dataZoom as Record<string, number>[];
    // 判断当前状态是否是原状态，如果是的话就更新红线，反之则是缩放状态，无需更新
    if (
      zoomInfo[0].startValue === lotStore.lotOptMinMax.xMin &&
      zoomInfo[0].endValue === lotStore.lotOptMinMax.xMax &&
      zoomInfo[1].startValue === lotStore.lotOptMinMax.yMin &&
      zoomInfo[1].endValue === lotStore.lotOptMinMax.yMax
    ) {
      opt.series[1].markLine.data = [
        [
          {
            coord: [lotStore.lotOptMinMax?.xMin, lotStore.sheet.headMd]
          },
          {
            coord: [lotStore.lotOptMinMax?.xMax, lotStore.sheet.headMd]
            // symbol: 'none',
          }
        ]
      ];
      setOptions(opt);
      myChartRef.current?.setOption(opt, { notMerge: true });
    }
  }, [lotStore.sheet.headMd]);

  // 6 数据为空的时候清空img图
  const emptyChart = () => {
    const opt = {
      ...optConfig
    };
    myChartRef.current?.setOption(opt, { notMerge: true });
  };

  useImperativeHandle(chartsProps.onRef, () => {
    return { emptyChart, changeOption };
  });

  return <div className="lot-flaw-map" ref={canvasRef}></div>;
};

export default observer(LotFlawMap);
